package com.mindainfo.groundwave.server.base.realm;

import com.mindainfo.groundwave.server.base.component.GlobalParams;
import com.mindainfo.groundwave.server.member.bean.SysMember;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by MD-01 on 2017/6/29.
 * 密码加密处理
 */
@Component
public class PasswordHelper {

    @Resource
    private GlobalParams globalParams;

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    public void encryptPassword(SysMember member) {

        String salt = randomNumberGenerator.nextBytes().toHex();
        GlobalParams.ShiroParams shiro = globalParams.getShiro();

        String newPassword = new SimpleHash(shiro.getPasswordAlgorithmName(),
                member.getPassword(),
                ByteSource.Util.bytes(salt),
                shiro.getPasswordHashIterations()).toHex();

        member.setSalt(salt);
        member.setPassword(newPassword);
    }

    /**
     * 根据输入密码和盐值得到加密后的密码
     */
    public String calculatePassword(String inputPassword,String salt){

        GlobalParams.ShiroParams shiro = globalParams.getShiro();
        String newPassword = new SimpleHash(shiro.getPasswordAlgorithmName(),
                inputPassword,
                ByteSource.Util.bytes(salt),
                shiro.getPasswordHashIterations())
                .toHex();
        return newPassword;
    }
}
